package com.android.fitcontrol;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;

import com.android.fitcontrol.bean.Training;
import com.android.fitcontrol.common.CommonUtils;
import com.android.fitcontrol.database.DBConnector;

public class ScheduleWeekActivity extends Activity {
	
	private CalendarView mCalendar;
	
	private DBConnector connector;
	
	
	@Override 
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		
		setContentView(R.layout.activity_week_schedule);
		
		ActionBar actionBar = getActionBar();
		//actionBar.setDisplayHomeAsUpEnabled(true);
		connector = new DBConnector(this);

		long currentDate = Calendar.getInstance().getTime().getTime();
		final Date _date = Calendar.getInstance().getTime();
		
		mCalendar = (CalendarView) findViewById(R.id.calendar);
		mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		mCalendar.setDate(currentDate, true, true);

		mCalendar.setOnDateChangeListener(new OnDateChangeListener() {
			
			public void onSelectedDayChange(CalendarView calendar, int year, int month,
					int dayOfMonth) {
				try {
					// check existed complex
					//
					Format formatter = new SimpleDateFormat("dd-MM-yyyy");
					String date = dayOfMonth + "-" + (month  + 1) + "-" + year;
					final Date resultDate = (Date) formatter.parseObject(date);

					if (!isCurrentWeek(resultDate)) {
						calendar.setDate(_date.getTime(), true, true);
					} else {
						_date.setTime(resultDate.getTime());
						final Intent exerciseListIntent = new Intent(
								ScheduleWeekActivity.this,
								ExerciseListActivity.class);
						exerciseListIntent
								.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						exerciseListIntent.putExtra("pickedDate",
								resultDate.getTime());
						String selection = Training.USER_ID + " = ? and "
								+ Training.DATE + " = ?";
						String[] args = new String[] {
								String.valueOf(CommonUtils.getUserId()),
								String.valueOf(resultDate.getTime()) };
						Cursor c = connector.query(Training.TABLE_NAME, null,
								selection, args, null, null, null);
						boolean isExistTraining = false;
						if (c.moveToFirst()) {
							isExistTraining = true;
							exerciseListIntent.putExtra("training_id",
									c.getInt(Training.NUM_ID));
						}
						c.close();

						if (!isExistTraining) {
							AlertDialog.Builder alertBuilder = new AlertDialog.Builder(
									ScheduleWeekActivity.this);
							alertBuilder
									.setTitle(
											R.string.schedule_week_dialog_title)
									.setNegativeButton("Cancel",
											new OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {

												}
											})
									.setPositiveButton("Create",
											new OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {
													Training tra = new Training();
													tra.setDate(resultDate
															.getTime());
													tra.setUser_ID(CommonUtils
															.getUserId());
													connector.insert(tra);
													String selection = Training.USER_ID
															+ " = "
															+ CommonUtils
																	.getUserId()
															+ " and "
															+ Training.DATE
															+ " = "
															+ resultDate
																	.getTime();
													Cursor c = connector
															.query(Training.TABLE_NAME,
																	null,
																	selection,
																	null, null,
																	null, null);
													c.moveToFirst();
													exerciseListIntent
															.putExtra(
																	"training_id",
																	c.getInt(Training.NUM_ID));
													c.close();
													startActivity(exerciseListIntent);
												}
											})
									.setMessage(
											"Do you want to create a new complex?")
									.show();

						} else {
							startActivity(exerciseListIntent);
						}
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		
		mCalendar.setOnLongClickListener(new OnLongClickListener() {
			
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				return false;
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onStop();
		connector.close();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case android.R.id.home:
			Intent backIntent = new Intent(this, ExerciseListActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;
		case R.id.action_bar_logout_item:
			connector.delete("user", -1);
			connector.close();
			Intent loginIntent = new Intent(this, LoginActivity.class);
			loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(loginIntent);
			finish();
			break;
		case R.id.action_bar_calendar_item:
			Intent monthScheduleIntent = new Intent(this, MonthScheduleActivity.class);
			monthScheduleIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(monthScheduleIntent);
			finish();
		}
		return true;
	}
	
	public void onDataPicked(View view) {
		
	}
	
	private boolean isCurrentWeek(Date date) {
		long today = Calendar.getInstance().getTime().getTime();
		long dayOfWeekSelected = date.getTime();
		
		long _diff = today - dayOfWeekSelected;
		if(_diff < 0)
			_diff = -1 * _diff;
		
		long weekDiff = 86400000 * 6;

		if (_diff > weekDiff)
			return false;
		else
			return true;
	}
}
